import React, {CSSProperties, useEffect, useMemo, useRef, useState} from "react";
import st from './home.module.css'
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import {addResume, deleteResumeById, getResumeCenterList} from "../../redux/resume-center";
import {Button, Card, Checkbox, Input, message, Modal} from "antd";
import {BuildTwoTone, DeleteTwoTone, FileAddTwoTone } from "@ant-design/icons";
import {useNavigate} from "react-router-dom";
import {
    reInitAvatar,
    reInitEduInfo,
    reInitialBasicInfo,
    reInitJobIntent,
    reInitProj,
    reInitSelfEvaluation,
    reInitSkills,
    reInitWorkInfo,
} from "../../redux";
import {reInitOrder} from "../../redux/order";

export const formatTime = (d: number) => {
    if (d === 0) {
        return '--'
    }
    const offsetTime = +new Date() - d;
    // 多少秒
    const s = Math.floor(offsetTime / 1000);
    // 一分钟秒数
    const ms = 60;
    // 一小时秒数
    const hs = ms * 60;
    // 一天秒数
    const ds = hs * 24;
    // 一月秒数
    const Ms = ds * 30;
    // 计算
    const M_ = Math.floor(s / Ms)
    const D_ = Math.floor( (s % Ms) / ds)
    const H_ = Math.floor( (s % ds) / hs)
    const MM_ = Math.floor( (s % hs) / ms)
    const S_ = s % ms
    let res = ''
    if (M_) {res += M_ + '个月'}
    if (D_) {res += D_ + '天'}
    if (H_) {res += H_ + '时'}
    if (MM_) {res += MM_ + '分'}
    if (S_) {res += S_ + '秒'}
    if (res === '') {
        return '刚刚'
    }
    return res += '前';
}

interface PropsType {
    open: boolean;
    titleConfirm: (title: string) => void;
    onCancel: () => void;
}
export const ResumeTitleModal: React.FC<PropsType> = ({
    titleConfirm, open, onCancel
                                                 }) => {
    const inpRef = useRef(null)
    // 自动聚焦输入框
    useEffect(() => {
        if (open && inpRef) {
            setTimeout(() => {
                inpRef.current.focus();
            }, 0)
        }
    }, [open])

    const [resumeTitle, setResumeTitle] = useState('');
    return <Modal
        centered={true}
        open={open}
        closeIcon={false}
        title={'简历名称'} cancelText={'取消'} okText={'确定'}
        onOk={e => {
          titleConfirm(resumeTitle);
        }}
        onCancel={onCancel}
    >
        <Input ref={inpRef} placeholder={'我的简历'} onKeyUp={(e) => {
            if (e.keyCode === 13) {
                titleConfirm(resumeTitle)
            }
        }} onChange={e => setResumeTitle(e.target.value)} />
    </Modal>
}

const imgWidth = 300;


const imgCssStyle: CSSProperties = {
    width: imgWidth, height: Math.sqrt(2) * imgWidth
}

export const Home: React.FC = () => {
    const resumeList = useAppSelector(getResumeCenterList);
    const dispatch = useAppDispatch();
    const nav = useNavigate();

    const [open, setOpen] = useState(false);
    const [editState, setEditState] = useState(false);
    const [checkedIdList, setCheckIdList] = useState([]);
    const timeList = useMemo(() =>
        resumeList.map(d => formatTime(d.updateDate)), [resumeList.length])

    // 消息提示
    const [messageApi, contextHolder] = message.useMessage();


    function checkChange(id: string) {
        setCheckIdList((curList) => {
            const idx = curList.findIndex(d => d === id);
            if (idx > -1) {
                return curList.filter(d => d !== id)
            } else {
                return [...curList, id]
            }
        })
    }


    return <div className={st['home-main']}>
        {contextHolder}
        <ResumeTitleModal
            onCancel={() => setOpen(false)}
            open={open}
            titleConfirm={(title) => {
                if (title === '') {
                    messageApi.warning('请输入简历名称！')
                    return;
                }
                if (resumeList.some(d => d.title === title)) {
                    messageApi.warning('简历名称不可重复！')
                    return;
                }
                dispatch(addResume({title}))
                setOpen(false)
        }}/>
        <div className={st['handle-bar']}>
            <Button onClick={() => {setOpen(true)}} >
                <FileAddTwoTone />
                添加简历
            </Button>
            <Button onClick={() => {
                setEditState(curState => !curState)
            }}>
                <BuildTwoTone />
                {editState ? '取消管理' : '管理'}
            </Button>
            <Button disabled={!editState || !checkedIdList.length} onClick={() => {
                if (!checkedIdList.length) {
                    return;
                }
                Modal.confirm({
                    type: 'warning',
                    centered: true,
                    content: (<span>确认要删除吗?</span>),
                    onOk: () => {
                        dispatch(deleteResumeById(checkedIdList))
                    },
                    okText: '删除',
                    cancelText: '取消',
                })
            }}>
                <DeleteTwoTone />
                删除
            </Button>
        </div>
        <div className={st['card-grid']}>
            {
                resumeList.map(d => ({...d, checked: false})).map((d, index) => (
                    <Card
                        key={d.id}
                        bordered={false}
                        bodyStyle={{
                            padding: '8px 16px',
                            borderTop: '1px solid #ccc',
                            background: '#564f4f'
                        }}
                        cover={
                            d.imgSrc ?
                            <img style={{...imgCssStyle}} alt='card-img' src={d.imgSrc} /> :
                            <div style={{
                                ...imgCssStyle,
                                display: "flex", justifyContent: "center", alignItems: 'center'
                            }}>
                                <span>暂无封面</span>
                            </div>
                        }
                        onClick={(e) => {
                            if (editState) {
                                checkChange(d.id)
                                return;
                            }
                            dispatch(reInitAvatar(d.avatar))
                            dispatch(reInitialBasicInfo(d.basic))
                            dispatch(reInitEduInfo(d.eduExperience))
                            dispatch(reInitSkills(d.skills))
                            dispatch(reInitJobIntent(d.jobIntent))
                            dispatch(reInitWorkInfo(d.workInfo))
                            dispatch(reInitProj(d.projectInfoList))
                            dispatch(reInitSelfEvaluation(d.selfEvaluation))
                            dispatch(reInitOrder(d.order))
                            // 路由切换
                            nav(`/resume?id=${d.id}`)
                        }}
                        hoverable={true}
                    >
                        <div className={st['card-title']}>
                            {d.title}
                            {
                                editState ?
                                    <Checkbox checked={checkedIdList.includes(d.id)}/>
                                    : null
                            }
                        </div>
                        <div className={st['update-time']}>
                            <span>更新时间：</span>
                            <span>{timeList[index] }</span>
                        </div>
                    </Card>
                ))
            }
        </div>
    </div>
}
